//
//  B_CommentListVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/9/9.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_CommentListVC.h"
#import "B_CommentListHeaderView.h"
#import "B_CommentListTVC.h"
#import "B_CommentListMoreTVC.h"
#import "B_CommentListFooterView.h"
#import "B_CommentListModel.h"
#import "B_UserMainPageVC.h"

@interface B_CommentListVC ()

@property (nonatomic, strong) BaseView * mainView;

@end

@implementation B_CommentListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"全部评论"];
    self.view = self.mainView;
    self.dataArray = [NSMutableArray array];
    [self getData:YES];
}

- (BaseView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseView alloc] init];
        [_mainView setTableViewFrameWithTop:5 left:0 right:0 bottom:0];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_CommentListTVC" bundle:nil] forCellReuseIdentifier:@"B_CommentListTVC"];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_CommentListMoreTVC" bundle:nil] forCellReuseIdentifier:@"B_CommentListMoreTVC"];
        
        _mainView.emptyShow = ^BOOL{
            if (weSelf.dataArray.count > 0) {
                return NO;
            }
            return YES;
        };
        _mainView.numberOfSectionsBlock = ^NSInteger(UITableView *tableView) {
            return weSelf.dataArray.count;
        };
        
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            B_CommentListModel * model = weSelf.dataArray[section];
            if (model.showAll) {
                return [model.twoCommentCount integerValue] > 4 ? [model.twoCommentCount integerValue] + 1 : [model.twoCommentCount integerValue];
            } else {
                return [model.twoCommentCount integerValue] > 4 ? 5 : [model.twoCommentCount integerValue];
            }
        };
        /// 组头
        _mainView.viewForHeaderBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            B_CommentListModel * model = weSelf.dataArray[section];
            B_CommentListHeaderView * header = [B_CommentListHeaderView initB_CommentListHeaderView];
            [header.B_userImageView sd_setImageWithURL:[NSURL URLWithString:model.portrait]];
            header.B_userName.text = model.nickName;
            if ([model.is_like isEqualToString:@"1"]) {
                header.B_likeButton.selected = YES;
            } else {
                header.B_likeButton.selected = NO;
            }
            [header.B_likeButton setTitle:safeValue1(model.likeCouont) forState:UIControlStateNormal];
            [header.B_likeButton setTitle:safeValue1(model.likeCouont) forState:UIControlStateSelected];
            [header.B_userTypeImageView setUsetType:model.userType];
            
            NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:model.content];
            string.yy_font = [UIFont systemFontOfSize:12];
            string.yy_lineHeightMultiple = 1.15;
            [string yy_setTextHighlightRange:string.yy_rangeOfAll
                                          color:[UIColor color_text_light_gray]
                                backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.20]
                                      tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){

                                          //TODO: 评论事件  一级评论
                                      }];
            
            header.B_commentLabel.attributedText = string;
            header.B_commentLabel.numberOfLines = 0;
            header.B_placeLabel.text = model.content;
            
            header.tapAction = ^{
                [weSelf likeAction:model];
            };
            return header;
        };
        // cell
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            B_CommentListModel * tmodel = weSelf.dataArray[indexPath.section];
            B_TopicTwoCommentListModel * model;
            if (tmodel.showAll) {
                if (indexPath.row == [tmodel.twoCommentCount integerValue]) {
                    /// 查看更多按钮
                    B_CommentListMoreTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_CommentListMoreTVC" forIndexPath:indexPath];
                    [cell.B_commentAllButton setTitle:[NSString stringWithFormat:@"共%@条评论 >", tmodel.twoCommentCount] forState:UIControlStateNormal];
                    cell.B_commentAllAction = ^{
                        tmodel.showAll = NO;
                        [weSelf.mainView.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                    };
                    return cell;
                } else {
                    model = tmodel.topicTwoCommentListArray[indexPath.row];
                }
            } else {
                if ([tmodel.twoCommentCount integerValue] > 4) {
                    if (indexPath.row == 4) {
                        /// 查看更多按钮
                        B_CommentListMoreTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_CommentListMoreTVC" forIndexPath:indexPath];
                        [cell.B_commentAllButton setTitle:[NSString stringWithFormat:@"共%@条评论 >", tmodel.twoCommentCount] forState:UIControlStateNormal];
                        cell.B_commentAllAction = ^{
                            tmodel.showAll = YES;
                            [weSelf.mainView.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
                        };
                        return cell;

                    } else {
                        model = tmodel.topicTwoCommentListArray[indexPath.row];
                    }
                } else {
                    model = tmodel.topicTwoCommentListArray[indexPath.row];
                }
            }
            ///
            B_CommentListTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_CommentListTVC" forIndexPath:indexPath];
            NSMutableAttributedString * text = [[NSMutableAttributedString alloc] init];
            {
            
                NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:safeValue3(model.userNickName)];
                string.yy_font = [UIFont systemFontOfSize:12];
                string.yy_lineHeightMultiple = 1.15;
                [string yy_setTextHighlightRange:string.yy_rangeOfAll
                                           color:[UIColor color_text_deep_gray]
                                 backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.20]
                                       tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                           NSLog(@"点击事件发生了");
                                           
                                           B_UserMainPageVC * vc = [[B_UserMainPageVC alloc] init];
                                           vc.B_userId = model.topicCommentUserId;
                                           [weSelf pushNextViewController:vc];
                                           
                                       }];
                [text appendAttributedString:string];
                
                if ([model.topicCommentByUserId isEqualToString:getUserId()]) {
                    
                    NSMutableAttributedString * string1 = [[NSMutableAttributedString alloc] initWithString:@":"];
                    string1.yy_font = [UIFont systemFontOfSize:12];
                    string1.yy_color = [UIColor color_text_white];
                    [text appendAttributedString:string1];
                    
                    NSMutableAttributedString * string2 = [[NSMutableAttributedString alloc] initWithString:model.content];
                    string2.yy_font = [UIFont systemFontOfSize:12];
                    string2.yy_lineHeightMultiple = 1.15;
                    [string2 yy_setTextHighlightRange:string2.yy_rangeOfAll
                                               color:[UIColor color_text_light_gray]
                                     backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.20]
                                           tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                               //TODO:评论内容的点击事件
                                           }];
                    [text appendAttributedString:string2];
                } else {
                    
                    NSMutableAttributedString * string4 = [[NSMutableAttributedString alloc] initWithString:@" 回复 "];
                    string4.yy_font = [UIFont systemFontOfSize:12];
                    string4.yy_color = [UIColor color_text_white];
                    [text appendAttributedString:string4];
                    
                    
                    NSMutableAttributedString * string1 = [[NSMutableAttributedString alloc] initWithString:safeValue3(model.byUserNickName)];
                    string1.yy_font = [UIFont systemFontOfSize:12];
                    string1.yy_lineHeightMultiple = 1.15;
                    [string1 yy_setTextHighlightRange:string1.yy_rangeOfAll
                                                color:[UIColor color_text_deep_gray]
                                      backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.20]
                                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                //TODO:被评论人点击事件
                                                B_UserMainPageVC * vc = [[B_UserMainPageVC alloc] init];
                                                vc.B_userId = model.topicCommentByUserId;
                                                [weSelf pushNextViewController:vc];
                                            }];
                    [text appendAttributedString:string1];
                    
                    
                    NSMutableAttributedString * string3 = [[NSMutableAttributedString alloc] initWithString:@": "];
                    string3.yy_font = [UIFont systemFontOfSize:12];
                    string3.yy_color = [UIColor color_text_white];
                    [text appendAttributedString:string3];
                    
                    NSMutableAttributedString * string2 = [[NSMutableAttributedString alloc] initWithString:model.content];
                    string2.yy_font = [UIFont systemFontOfSize:12];
                    string2.yy_lineHeightMultiple = 1.15;
                    [string2 yy_setTextHighlightRange:string2.yy_rangeOfAll
                                                color:[UIColor color_text_light_gray]
                                      backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.20]
                                            tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                //TODO:评论内容的点击事件
                                                
                                            }];
                    [text appendAttributedString:string2];
                    
                }
            }
            cell.B_commentLabel.attributedText = text;
            cell.B_commentLabel.numberOfLines = 0;
            
            cell.B_placeLabel.attributedText = text;
            return cell;
        };
        
        _mainView.viewForFooterBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            B_CommentListModel * model = weSelf.dataArray[section];
            B_CommentListFooterView * footer = [B_CommentListFooterView initB_CommentListFooterView];
            footer.B_timeLabel.text = [NSObject getTimeTo:model.createTime];
            return footer;
        };
        
        [_mainView setTableViewHeaderFresh:^{
            [weSelf getData:YES];
        }];
        [_mainView setTableViewFooterFresh:^{
            [weSelf getData:NO];
        }];
        
    }
    return _mainView;
}

- (void) getData:(BOOL) isRefresh {
    if (isRefresh) {
        self.index = 1;
    } else {
        self.index ++;
    }
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/topic/selectTopicCommentList/%@/%@/%ld/10", self.topicId, getUserId(), self.index /**/] parameters:nil isCache:NO succeed:^(id data) {
        [weSelf.mainView endRefresh];
        if ([data[@"code"] isEqualToString:@"20010"]) {
            if (isRefresh) {
                [weSelf.dataArray removeAllObjects];
            }
            for (NSDictionary * dictionary in data[@"values"]) {
                B_CommentListModel * model = [B_CommentListModel mj_objectWithKeyValues:dictionary];
                model.topicTwoCommentListArray = [NSMutableArray array];
                for (NSDictionary * dic in model.topicTwoCommentList) {
                    B_TopicTwoCommentListModel * twoModel = [B_TopicTwoCommentListModel mj_objectWithKeyValues:dic];
                    [model.topicTwoCommentListArray addObject:twoModel];
                }
                [weSelf.dataArray addObject:model];
            }
            
            [weSelf.mainView.tableView reloadData];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [weSelf.mainView endRefresh];
        [KeyWindow makeToast:@"服务员异常"];
    }];
}

/**
 TODO:评论的点赞
 
 @param model 模型
 */
- (void) likeAction:(B_CommentListModel *) model {
    ///yearnfor/inter/topicCommentLike/addCommentLike/1/1
    
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/topicCommentLike/addCommentLike/%@/%@", model.id, getUserId()] parameters:nil isCache:NO succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20005"]) {
            [KeyWindow makeToast:@"操作成功"];
            if ([model.is_like isEqualToString:@"1"]) {
                model.is_like = @"2";
                model.likeCouont = [NSString stringWithFormat:@"%ld", [model.likeCouont integerValue] - 1];
            } else {
                model.is_like = @"1";
                model.likeCouont = [NSString stringWithFormat:@"%ld", [model.likeCouont integerValue] + 1];
            }
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
        [weSelf.mainView.tableView reloadData];
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
